'use client';

import React from 'react';
import { useRouter } from 'next/navigation';
import { Spin, Result, Button } from 'antd';
import { useAuth } from '@/contexts/AuthContext';
import { ProtectedRouteProps } from '@/types/auth';
import { hasRole, hasPermission } from '@/utils/auth';

const ProtectedRoute: React.FC<ProtectedRouteProps> = ({
  children,
  requiredRoles = [],
  fallback,
}) => {
  const { user, isLoading, isAuthenticated } = useAuth();
  const router = useRouter();

  // 加载中
  if (isLoading) {
    return (
      <div style={{
        display: 'flex',
        justifyContent: 'center',
        alignItems: 'center',
        height: '100vh',
      }}>
        <Spin size="large" />
      </div>
    );
  }

  // 未登录
  if (!isAuthenticated || !user) {
    if (fallback) {
      return <>{fallback}</>;
    }
    
    return (
      <Result
        status="403"
        title="未登录"
        subTitle="请先登录您的账户"
        extra={
          <Button type="primary" onClick={() => router.push('/login')}>
            去登录
          </Button>
        }
      />
    );
  }

  // 检查角色权限
  if (requiredRoles.length > 0 && !hasRole(user, requiredRoles)) {
    if (fallback) {
      return <>{fallback}</>;
    }

    return (
      <Result
        status="403"
        title="权限不足"
        subTitle={`您需要以下角色之一：${requiredRoles.join(', ')}`}
        extra={
          <Button type="primary" onClick={() => router.back()}>
            返回
          </Button>
        }
      />
    );
  }

  return <>{children}</>;
};

export default ProtectedRoute; 